package com.bbx.taxi.client.DB.UnprocessedList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;

import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialOrderDetail;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OrderInfo;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.UnprocessedList.UnprocessedList;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.End;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Location;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Locations;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrderList;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Start;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.DB.MyOrder.MyOrderLocationsDB;
import com.bbx.taxi.client.DB.Util.DBHelper;
import com.bbx.taxi.client.DB.Util.DBcolumns;
/** 
 * @Path com.bbx.taxi.client.DB.UnprocessedList.UnprocessedRecordDB.java
 * @Author 严旭文
 * @Date 2016-1-26 下午5:31:16
 * @Company 蓝海（福建）信息技术有限公司
 * @Description
 * 审核记录
 */
public class UnprocessedRecordDB implements DBcolumns {
	private DBHelper helper;

	public UnprocessedRecordDB(Context context) {
		MyApplication myApplication=MyApplication.getInstance();
		helper = DBHelper.getInstance(context,myApplication.getUid());
	}

	/**
	 * 打开只读的数据库
	 */
	public SQLiteDatabase onOpenRead() {
		SQLiteDatabase SQLdb = helper.getReadableDatabase();
		return SQLdb;
	}

	/**
	 * 打开只写的数据库
	 */
	public SQLiteDatabase onOpenWrite() {
		SQLiteDatabase SQLdb = helper.getWritableDatabase();
		return SQLdb;
	}

	/**
	 * 查询全部
	 */
	public Cursor onQuery() {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = SQLdb.query(TABLE_UNPROCESSED_RECORD, null, null, null, null,
				null, UNPROCESSED_RECORD_id + " desc ");
		return cursor;

	}

	/**
	 * 根据订单id查询
	 */
	public Cursor onQuery(String order_id) {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = SQLdb.query(TABLE_UNPROCESSED_RECORD, null, UNPROCESSED_RECORD_ORDER_ID
				+ "='" + order_id + "'", null, null, null, UNPROCESSED_RECORD_id
				+ " desc ");
		return cursor;

	}

	/**
	 * 用于分页查询，指定数量，指定id,按降序查询，不能大于id
	 */
	public Cursor onQuery(int id, int count) {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = null;
		if (id == -1) {
			cursor = SQLdb.query(TABLE_UNPROCESSED_RECORD, null, null, null, null, null,
					UNPROCESSED_RECORD_id + " desc  LIMIT 0," + count);
		} else {
			cursor = SQLdb.query(TABLE_UNPROCESSED_RECORD, null, UNPROCESSED_RECORD_id + "<" + id,
					null, null, null, UNPROCESSED_RECORD_id + " desc  LIMIT " + count);
		}

		return cursor;

	}

	/**
	 * 删除整个表
	 */
	public void onDelete() {
		SQLiteDatabase SQLdb = onOpenWrite();
		SQLdb.delete(TABLE_UNPROCESSED_RECORD, null, null);
		SQLdb.close();
	}

	/**
	 * 删除订单Id
	 */
	public void onDelete(Context context, String order_id) {
		SQLiteDatabase SQLdb = onOpenWrite();
		String[] whereArgs = { String.valueOf(order_id) };
		int i = SQLdb.delete(TABLE_UNPROCESSED_RECORD, UNPROCESSED_RECORD_ORDER_ID + "='" + order_id
				+ "'", null);
		SQLdb.close();
//		// 也要删除MyOrderLocationsDB表，以免数据太多
//		MyOrderLocationsDB db_locations = new MyOrderLocationsDB(context);
//		db_locations.onDelete(order_id);
	}
	/**
	 * 更新全部数据
	 */
	public void onUpdate(UnprocessedList mUnprocessedList){
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues cv = new ContentValues();
		cv.put(UNPROCESSED_RECORD_ORDER_ID,mUnprocessedList.getOrder_id());	
		cv.put(UNPROCESSED_RECORD_PASSENGER_ID, mUnprocessedList.getPassenger_id());	
		cv.put(UNPROCESSED_RECORD_PURPOSE,mUnprocessedList.getPurpose());	
		cv.put(UNPROCESSED_RECORD_ROUND_TRIP, mUnprocessedList.getOrderInfo().getRound_trip());	
		cv.put(UNPROCESSED_RECORD_VEHICLE_ID, mUnprocessedList.getOrderInfo().getVehicle_type_id());
		cv.put(UNPROCESSED_RECORD_DRIVER_ID,mUnprocessedList.getOrderInfo().getDriver_id());	
		cv.put(UNPROCESSED_RECORD_DRIVER_NAME, mUnprocessedList.getOrderInfo().getDriver_name());	
		cv.put(UNPROCESSED_RECORD_PRICE, mUnprocessedList.getOrderInfo().getPrice());	
		cv.put(UNPROCESSED_RECORD_APPOINT_TIME,mUnprocessedList.getOrderInfo().getAppoint_time());	
//		cv.put(UNPROCESSED_RECORD_PASS_STATUS,1);	
		SQLdb.update(TABLE_UNPROCESSED_RECORD, cv, UNPROCESSED_RECORD_ORDER_ID + "='" + mUnprocessedList.getOrder_id()
				+ "'", null);
		SQLdb.close();
	}
	/**
	 * 更新一条数据
	 */
	public void onUpdate(String id, String order_id, String passenger_id,String purpose,int is_round,String vehicle_id
			,String driver_id,String driver_name,int price,String time) {
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues cv = new ContentValues();
		cv.put(UNPROCESSED_RECORD_ORDER_ID,order_id);	
		cv.put(UNPROCESSED_RECORD_PASSENGER_ID, passenger_id);	
		cv.put(UNPROCESSED_RECORD_PURPOSE,purpose);	
		cv.put(UNPROCESSED_RECORD_ROUND_TRIP, is_round);	
		cv.put(UNPROCESSED_RECORD_VEHICLE_ID,vehicle_id);
		cv.put(UNPROCESSED_RECORD_DRIVER_ID,driver_id);	
		cv.put(UNPROCESSED_RECORD_DRIVER_NAME,driver_name);	
		cv.put(UNPROCESSED_RECORD_PRICE, price);	
		cv.put(UNPROCESSED_RECORD_APPOINT_TIME,time);
//		cv.put(UNPROCESSED_RECORD_PASS_STATUS,1);	
		SQLdb.update(TABLE_UNPROCESSED_RECORD, cv, UNPROCESSED_RECORD_id + "=" + id, null);
		SQLdb.close();
	}

	/**
	 * 更新一条数据,根据order_id修改评价状态
	 */
	public void onUpdateValuate(String myorder_id, int valuate_status) {
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues cv = new ContentValues();
		cv.put(MYORDER_VALUATE_STATUS, valuate_status);
		SQLdb.update(TABLE_UNPROCESSED_RECORD, cv, MYORDER_ORDER_ID + "='" + myorder_id
				+ "'", null);
		SQLdb.close();
	}
	/**
	 * 插入一条数据
	 */
	public void onWrite( String order_id, String passenger_id,String purpose,String is_round,String vehicle_id
			,String driver_id,String driver_name,int price,String time,String ispass) {
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues values = new ContentValues();
		values.put(UNPROCESSED_RECORD_ORDER_ID,order_id);	
		values.put(UNPROCESSED_RECORD_PASSENGER_ID, passenger_id);	
		values.put(UNPROCESSED_RECORD_PURPOSE,purpose);	
		values.put(UNPROCESSED_RECORD_ROUND_TRIP,is_round);	
		values.put(UNPROCESSED_RECORD_VEHICLE_ID,vehicle_id);
		values.put(UNPROCESSED_RECORD_DRIVER_ID,driver_id);	
		values.put(UNPROCESSED_RECORD_DRIVER_NAME, driver_name);	
		values.put(UNPROCESSED_RECORD_PRICE,price);	
		values.put(UNPROCESSED_RECORD_APPOINT_TIME,time);	
		values.put(UNPROCESSED_RECORD_PASS_STATUS,ispass);	
		SQLdb.insert(TABLE_UNPROCESSED_RECORD, UNPROCESSED_RECORD_id, values);
		SQLdb.close();
	}

	/**
	 * 关闭数据库
	 */
	public void onColse() {
		SQLiteDatabase SQLdb = onOpenWrite();
		SQLdb.close();
	}

	/**
	 * 写入全部订单数据（单笔）
	 */
	public void onWriteDB(Context context, UnprocessedList mUnprocessedList) {
		MyOrderLocationsDB db_locations = new MyOrderLocationsDB(context);
		String order_id = mUnprocessedList.getOrder_id();
		String passenger_id = mUnprocessedList.getPassenger_id();
		String purpose = mUnprocessedList.getPurpose();
		String is_round = mUnprocessedList.getOrderInfo().getRound_trip();
		String vehicle_id =  mUnprocessedList.getOrderInfo().getVehicle_type_id();
		String driver_id = mUnprocessedList.getOrderInfo().getDriver_id();
		String driver_name = mUnprocessedList.getOrderInfo().getDriver_name();
		int price = mUnprocessedList.getOrderInfo().getPrice();
		String time = mUnprocessedList.getOrderInfo().getAppoint_time();
		String  ispass = mUnprocessedList.getProcessResult();
		onWrite( order_id,  passenger_id, purpose, is_round, vehicle_id
				, driver_id, driver_name, price, time,ispass);
		//写入Location表
			String start_address = mUnprocessedList.getOrderDetail().getStart().getAddress();
			double start_lng = mUnprocessedList.getOrderDetail().getStart()
					.getLocation().getLng();
			double start_lat = mUnprocessedList.getOrderDetail().getStart()
					.getLocation().getLat();
			String start_name = mUnprocessedList.getOrderDetail().getStart()
					.getName();
			String start_phone = mUnprocessedList.getOrderDetail().getStart()
					.getPhone();
			String end_address = mUnprocessedList.getOrderDetail().getEnd()
					.getAddress();
			double end_lng = mUnprocessedList.getOrderDetail().getEnd()
					.getLocation().getLng();
			double end_lat = mUnprocessedList.getOrderDetail().getEnd()
					.getLocation().getLat();
			String end_name = mUnprocessedList.getOrderDetail().getEnd()
					.getName();
			String end_phone = mUnprocessedList.getOrderDetail().getEnd()
					.getPhone();
			int volume = 0;
			int weight = 0;
			int count= 0;
			int mutiple_oncar= 0;
			
			db_locations.onWrite(order_id, start_address, start_lng, start_lat,
					start_name, start_phone, end_address, end_lng, end_lat,
					end_name, end_phone,volume,weight,count,mutiple_oncar);
		
	}

	/**
	 * 写入（多笔）必须是所有的数据
	 */
	public void onWriteDB(final Context context, final ArrayList<UnprocessedList> list,final boolean isDelete,final Handler mHandler) {
		new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... params) {
				MyOrderLocationsDB db_locations = new MyOrderLocationsDB(context);
				if(isDelete){
				   onDelete();
				}
				for (int i = list.size() - 1; i >= 0; i--) {// 逆序插入，因为list最新数据在在第一个，数据库的ID要最大，所以要逆序
					String order_id = list.get(i).getOrder_id();
					String passenger_id = list.get(i).getPassenger_id();
					String purpose = list.get(i).getPurpose();
					String is_round = list.get(i).getOrderInfo().getRound_trip();
					String vehicle_id =  list.get(i).getOrderInfo().getVehicle_type_id();
					String driver_id = list.get(i).getOrderInfo().getDriver_id();
					String driver_name = list.get(i).getOrderInfo().getDriver_name();
					int price = list.get(i).getOrderInfo().getPrice();
					String time = list.get(i).getOrderInfo().getAppoint_time();
					String  ispass = list.get(i).getProcessResult();
					onWrite( order_id,  passenger_id, purpose, is_round, vehicle_id
							, driver_id, driver_name, price, time,ispass);
				    //写入Locations表
						String start_address = list.get(i).getOrderDetail()
								.getStart().getAddress();
						double start_lng = list.get(i).getOrderDetail().getStart()
								.getLocation().getLng();
						double start_lat = list.get(i).getOrderDetail().getStart()
								.getLocation().getLat();
						String start_name = list.get(i).getOrderDetail()
								.getStart().getName();
						String start_phone = list.get(i).getOrderDetail()
								.getStart().getPhone();
						String end_address = list.get(i).getOrderDetail().getEnd()
								.getAddress();
						double end_lng = list.get(i).getOrderDetail().getEnd()
								.getLocation().getLng();
						double end_lat = list.get(i).getOrderDetail().getEnd()
								.getLocation().getLat();
						String end_name = list.get(i).getOrderDetail().getEnd()
								.getName();
						String end_phone = list.get(i).getOrderDetail().getEnd()
								.getPhone();
						int volume = 0;
						int weight = 0;
						int count= 0;
						int mutiple_oncar= 0;
						
						db_locations.onWrite(order_id, start_address, start_lng,
								start_lat, start_name, start_phone, end_address,
								end_lng, end_lat, end_name, end_phone,volume,weight,count,mutiple_oncar);
				}
				if(mHandler!=null)
					mHandler.sendEmptyMessage(BaseBBXActivity.MSG_ORDER_WRITE);
				return null;
			}}.execute();
	}

	/**
	 * 根据订单ID查询并返回UnprocessedList数据
	 */
	public UnprocessedList onReadDB(Context context, String order_id) {
		if(order_id==null)return null;
		MyOrderLocationsDB db_locations = new MyOrderLocationsDB(context);
		UnprocessedList mUnprocessedList = new UnprocessedList();
		Cursor c = onQuery(order_id);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				mUnprocessedList.setOrder_id(map.get(DBcolumns.UNPROCESSED_RECORD_ORDER_ID));
				mUnprocessedList.setPassenger_id(map.get(DBcolumns.UNPROCESSED_RECORD_PASSENGER_ID));
				mUnprocessedList.setPurpose(map.get(DBcolumns.UNPROCESSED_RECORD_PURPOSE));
				OrderInfo mOrderInfo=new OrderInfo();
				mOrderInfo.setRound_trip(map.get(DBcolumns.UNPROCESSED_RECORD_ROUND_TRIP));
				mOrderInfo.setVehicle_type_id(map.get(DBcolumns.UNPROCESSED_RECORD_VEHICLE_ID));
				mOrderInfo.setDriver_id(map.get(DBcolumns.UNPROCESSED_RECORD_DRIVER_ID));
				mOrderInfo.setDriver_name(map.get(DBcolumns.UNPROCESSED_RECORD_DRIVER_NAME));
				mOrderInfo.setPrice(Integer.parseInt(map.get(DBcolumns.UNPROCESSED_RECORD_PRICE)));
				mOrderInfo.setAppoint_time(map.get(DBcolumns.UNPROCESSED_RECORD_APPOINT_TIME));
				mUnprocessedList.setOrderInfo(mOrderInfo);
				mUnprocessedList.setProcessResult(map.get(DBcolumns.UNPROCESSED_RECORD_PASS_STATUS));
			} while (c.moveToNext());
		}
		c.close();
		onColse();
		
		OfficialOrderDetail mOfficialOrderDetail = new OfficialOrderDetail();
		Cursor c2 = db_locations.onQuery(order_id);
		c2.moveToFirst();
		if (c2.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c2.getColumnCount(); i++) {
					map.put(c2.getColumnName(i), c2.getString(i));
				}		
				Start start = new Start();
				start.setAddress(map
						.get(DBcolumns.MYORDER_LOCATIONS_START_ADDRESS));
				start.setName(map.get(DBcolumns.MYORDER_LOCATIONS_START_NAME));
				start.setPhone(map.get(DBcolumns.MYORDER_LOCATIONS_START_PHONE));
				Location mLocation_start = new Location();
				mLocation_start.setLat(Double.parseDouble(map
						.get(DBcolumns.MYORDER_LOCATIONS_START_LAT)));
				mLocation_start.setLng(Double.parseDouble(map
						.get(DBcolumns.MYORDER_LOCATIONS_START_LNG)));			
				start.setLocation(mLocation_start);
				End end = new End();
				end.setAddress(map.get(DBcolumns.MYORDER_LOCATIONS_END_ADDRESS));
				end.setName(map.get(DBcolumns.MYORDER_LOCATIONS_END_NAME));
				end.setPhone(map.get(DBcolumns.MYORDER_LOCATIONS_END_PHONE));
				Location mLocation_end = new Location();
				mLocation_end.setLat(Double.parseDouble(map
						.get(DBcolumns.MYORDER_LOCATIONS_END_LAT)));
				mLocation_end.setLng(Double.parseDouble(map
						.get(DBcolumns.MYORDER_LOCATIONS_END_LNG)));
				end.setLocation(mLocation_end);
				mOfficialOrderDetail.setStart(start);
				mOfficialOrderDetail.setEnd(end);
			} while (c2.moveToNext());
			c2.close();
			db_locations.onColse();
			mUnprocessedList.setOrderDetail(mOfficialOrderDetail);
		}
		return mUnprocessedList;
	}

	/**
	 * 读取全部订单数据库数据,根据类型
	 */
	public ArrayList<UnprocessedList> onReadDB(Context context, int num) {
		MyOrderLocationsDB db_locations = new MyOrderLocationsDB(context);
		ArrayList<UnprocessedList> list_all = new ArrayList<UnprocessedList>();
		Cursor c = onQuery(-1, num);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				UnprocessedList mUnprocessedList = new UnprocessedList();
				mUnprocessedList.setOrder_id(map.get(DBcolumns.UNPROCESSED_RECORD_ORDER_ID));
				mUnprocessedList.setPassenger_id(map.get(DBcolumns.UNPROCESSED_RECORD_PASSENGER_ID));
				mUnprocessedList.setPurpose(map.get(DBcolumns.UNPROCESSED_RECORD_PURPOSE));
				OrderInfo mOrderInfo=new OrderInfo();
				mOrderInfo.setRound_trip(map.get(DBcolumns.UNPROCESSED_RECORD_ROUND_TRIP));
				mOrderInfo.setVehicle_type_id(map.get(DBcolumns.UNPROCESSED_RECORD_VEHICLE_ID));
				mOrderInfo.setDriver_id(map.get(DBcolumns.UNPROCESSED_RECORD_DRIVER_ID));
				mOrderInfo.setDriver_name(map.get(DBcolumns.UNPROCESSED_RECORD_DRIVER_NAME));
				mOrderInfo.setPrice(Integer.parseInt(map.get(DBcolumns.UNPROCESSED_RECORD_PRICE)));
				mOrderInfo.setAppoint_time(map.get(DBcolumns.UNPROCESSED_RECORD_APPOINT_TIME));
				mUnprocessedList.setOrderInfo(mOrderInfo);
				mUnprocessedList.setProcessResult(map.get(DBcolumns.UNPROCESSED_RECORD_PASS_STATUS));
				list_all.add(mUnprocessedList);
			} while (c.moveToNext());
		}
		c.close();
		onColse();
		// 读取Locations表
		for (int j = 0; j < list_all.size(); j++) {
			OfficialOrderDetail mOfficialOrderDetail = new OfficialOrderDetail();
			Cursor c2 = db_locations.onQuery(list_all.get(j).getOrder_id());
			c2.moveToFirst();
			if (c2.getCount() > 0) {
				do {
					Map<String, String> map = new HashMap<String, String>();
					for (int i = 0; i < c2.getColumnCount(); i++) {
						map.put(c2.getColumnName(i), c2.getString(i));
					}
					
					Start start = new Start();
					start.setAddress(map
							.get(DBcolumns.MYORDER_LOCATIONS_START_ADDRESS));
					start.setName(map.get(DBcolumns.MYORDER_LOCATIONS_START_NAME));
					start.setPhone(map.get(DBcolumns.MYORDER_LOCATIONS_START_PHONE));
					Location mLocation_start = new Location();
					mLocation_start.setLat(Double.parseDouble(map
							.get(DBcolumns.MYORDER_LOCATIONS_START_LAT)));
					mLocation_start.setLng(Double.parseDouble(map
							.get(DBcolumns.MYORDER_LOCATIONS_START_LNG)));			
					start.setLocation(mLocation_start);
					End end = new End();
					end.setAddress(map.get(DBcolumns.MYORDER_LOCATIONS_END_ADDRESS));
					end.setName(map.get(DBcolumns.MYORDER_LOCATIONS_END_NAME));
					end.setPhone(map.get(DBcolumns.MYORDER_LOCATIONS_END_PHONE));
					Location mLocation_end = new Location();
					mLocation_end.setLat(Double.parseDouble(map
							.get(DBcolumns.MYORDER_LOCATIONS_END_LAT)));
					mLocation_end.setLng(Double.parseDouble(map
							.get(DBcolumns.MYORDER_LOCATIONS_END_LNG)));
					end.setLocation(mLocation_end);
					mOfficialOrderDetail.setStart(start);
					mOfficialOrderDetail.setEnd(end);
				} while (c2.moveToNext());
			}
			list_all.get(j).setOrderDetail(mOfficialOrderDetail);
			c2.close();
			db_locations.onColse();
		}
		return list_all;
	}
}
